extends ProgressBar

var k1: int = 1
var k2: int = 2
var max_player_level: int = 20
var current_level: int = 1
var current_level_exp: int = 0
var max_exp_for_current_level: int = 0

signal player_level_maxed

func _ready() -> void:
	update_level_and_exp_from_total()
	update_experience_display()

func calculate_total_exp_for_level(level: int) -> int:
	if level <= 0: return 0
	var exp_needed = round(k1 * float(level) + k2 * float(level) * float(level))
	return exp_needed

func update_level_and_exp_from_total() -> void:
	var total_exp = global.ex
	var level_check = 1
	while level_check < max_player_level:
		var exp_needed_for_next_level = calculate_total_exp_for_level(level_check)
		if total_exp < exp_needed_for_next_level:
			break
		level_check += 1
	current_level = min(level_check, max_player_level)
	var exp_at_previous_level_start = 0
	if current_level > 1:
		exp_at_previous_level_start = calculate_total_exp_for_level(current_level - 1)
	current_level_exp = total_exp - exp_at_previous_level_start
	max_exp_for_current_level = calculate_total_exp_for_level(current_level)
	if current_level == max_player_level:
		current_level_exp = max_exp_for_current_level

func update_experience_display() -> void:
	max_value = max_exp_for_current_level
	value = current_level_exp

func update_from_global() -> void:
	update_level_and_exp_from_total()
	update_experience_display()
	if current_level >= max_player_level:
		emit_signal("player_level_maxed")

func _on_player_max_level_reached() -> void:
	if current_level == max_player_level:
		update_level_and_exp_from_total()
		update_experience_display()
